package goserve

import (
	"log"
	"net/http"
	"os"
	"time"

	"gitee.com/joseelin/alifunserve"
	"gitee.com/joseelin/goserve/router"
	"github.com/go-chi/chi"
)

type App interface {
	Mux() *http.ServeMux
	Router() chi.Router
	Listen(defaultPort string, stripPrefix string, fun func() error) error
}

type app struct {
	mux    *http.ServeMux
	router chi.Router
}

func NewApp() App {
	return &app{
		mux:    http.NewServeMux(),
		router: router.New(),
	}
}
func (self *app) Mux() *http.ServeMux {
	return self.mux
}
func (self *app) Router() chi.Router {
	return self.router
}
func (self *app) init() error {
	log.SetFlags(log.Llongfile | log.LUTC)     //设置 LOG 格式
	time.Local = time.FixedZone("CST", 3600*8) //设置时区
	return nil
}

func (self *app) Listen(defaultPort string, stripPrefix string, fun func() error) error {
	self.init()
	port, ok := os.LookupEnv("FC_SERVER_PORT")
	if !ok {
		port = defaultPort
		if fun != nil {
			if err := fun(); err != nil {
				return err
			}
		}
	}
	ali := alifunserve.New(self.mux, fun, stripPrefix)
	return http.ListenAndServe(":"+port, ali)
}
